//
//  HCComposeTextView.swift
//  Hweibome
//
//  Created by apple on 15/12/15.
//  Copyright © 2015年 hechuan. All rights reserved.
//

import UIKit

@IBDesignable class HCComposeTextView: UITextView {

 @IBInspectable var placeholder: String? {
        didSet{
            placeholderLabel.text = placeholder
         //   placeholderLabel.sizeToFit()
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    override var text: String? {
        didSet{
            placeholderLabel.hidden = hasText()
        }
    }
    required init?(coder aDecoder: NSCoder) {
      //  fatalError("init(coder:) has not been implemented")         ???为什么
        super.init(coder: aDecoder)
        setupUI()
    }
    private func setupUI(){
      //  backgroundColor = RandomColor()
        addSubview(placeholderLabel)
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -10))
        //KVO
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChanged", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    @objc private func textChanged() {
      //  printLog("文字改变啦~~啦啦啦")
        placeholderLabel.hidden = hasText()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderLabel.x = 5
        placeholderLabel.y = 8
    }
    
    private lazy var placeholderLabel : UILabel = {
       let label = UILabel()
        label.numberOfLines = 0
        label.text = "wojiushizhu"
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.lightGrayColor()
        label.sizeToFit()
        return label
    }()
    
    
}
